﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using ObjectModel.PowerPoint.RulesModel;
using System.Xml.Serialization;

namespace ObjectModel.PowerPoint
{
    public class DataLinkCollection : ObservableCollection<DataLink>
    {
        DataLink mSelectedItem;
        SlideEvents mEvents;

        public DataLinkCollection() // Parameterless constructor needed for serialization.
        {
            HookUpEvents();
        }
        
        public DataLinkCollection(Ppt.Slide slide)
        {
            StoredSlide = new CachedSlide(slide);

            HookUpEvents();
        }

        public CachedSlide StoredSlide { get; set; }

        public DataLink SelectedItem
        {
            get { return mSelectedItem; }
            set
            {
                mSelectedItem = value;
                RunWithoutEvents(mSelectedItem.Target.Select);
            }
        }
        
        public void UpdateAll()
        {
            foreach (DataLink link in this)
                link.UpdateValues();
        }

        void HookUpEvents()
        {
            mEvents = StoredSlide.Slide.GetEvents();
            mEvents.ShapeSelected += OnShapeSelected;
        }

        void RunWithoutEvents(System.Action action)
        {
            mEvents.ShapeSelected -= OnShapeSelected;
            action();
            mEvents.ShapeSelected += OnShapeSelected;
        }

        void OnShapeSelected(object sender, ShapeChangedEventArgs e)
        {
            DataLink selItem = null;

            try { selItem = this.Single(l => l.Target.IsSelected); }
            catch (InvalidOperationException) { }

            //if (e.ShapeInfo.SlideId == Slide.SlideId)
            //foreach (DataLink link in this)
            //    if (link.Target.IsSelected)
            //        selItem = link;

            SelectedItem = selItem;
        }
    }
}
